<!--
 * @Author: HeAo
 * @Date: 2021-10-18 11:15:08
 * @LastEditTime: 2021-10-18 12:19:29
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2103code\3-2-Vue\day08\router-vuex\index.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../../js/vue.js"></script>
  <script src="../../js/vuex.js"></script>
  <script src="../../js/vue-router.js"></script>
  <script src="../../js/qs.js"></script>
  <script src="../../js/axios.js"></script>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入组件库 -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>
  <div id="app">
    <router-view></router-view>

  </div>
  <script>
    axios.defaults.baseURL = 'http://47.94.46.113:8888'
    let { mapState, mapActions } = Vuex

    // 1.声明组件
    let comLogin = {
      data() {
        return {
          loginData: {}
        }
      },
      methods: {
        ...mapActions('login', ['login']),
        toLogin() {
          // 判断当前登录输入框值是否全部输入
          if (this.loginData.username && this.loginData.password) {
            // 调用状态机中的actions
            this.login(this.loginData).then(res => {
              sessionStorage.setItem('token', res.data.data.token)
              // 登录成功后，跳转至首页
              this.$router.push('/index')
            })
          } else {
            alert('用户名和密码不能为空')
          }
        }
      },
      template: `
        <div>
          <h3>欢迎您，请登录！</h3>
          <el-form :model="loginData" label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="loginData.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginData.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="toLogin" type="primary">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      `
    }
    let comIndex = {
      data() {
        return {}
      },
      methods: {
        logoutHandler() {
          sessionStorage.removeItem('token')
          this.$router.push('/login')
        }
      },
      template: `
        <div>
          <h3>欢迎使用<el-button @click="logoutHandler">退出</el-button></h3>
          <el-button @click="$router.push('/index/category')" type="primary">栏目管理</el-button>
          <el-button type="primary">文章管理</el-button>
          <router-view></router-view>
        </div>
      `
    }
    let comCategory = {
      data() {
        return {}
      },
      computed: {
        ...mapState('category', ['categories'])
      },
      template: `
        <div>
          <el-table :data="categories" style="width: 100%;">
            <el-table-column prop="name" label="栏目名称"></el-table-column>
          </el-table>
        </div>
      `,
      methods: {
        ...mapActions('category', ['findAllCategories']),

      },
      created() {
        this.findAllCategories()
      }
    }

    // 2.声明路由实例
    let router = new VueRouter({
      routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: comLogin },
        {
          path: '/index',
          component: comIndex,
          children: [
            { path: 'category', component: comCategory }
          ]
        },
      ]
    })
    // 2.1路由的全局守卫
    router.beforeEach((to, from, next) => {
      // 获取token
      const token = sessionStorage.getItem('token')
      if (to.path != '/login' && !token) {
        alert('请先登录！')
        // 未登录状态下直接通过修改url地址的形式跳转至首页
        // 使用守卫拦截，并且强行返回到登录页面
        next('/login')
      } else {
        next()
      }
    })

    let moduleLogin = {
      namespaced: true,
      state() {
        return {
          token: null
        }
      },
      actions: {
        async login(context, data) {
          let res = await axios.post('/user/login', data)
          return res
        }
      }
    }

    let moduleCategory = {
      namespaced: true,
      state() {
        return {
          categories: []
        }
      },
      mutations: {
        SET_CATEGORY(state, payload) {
          state.categories = payload
        }
      },
      actions: {
        async findAllCategories({ commit }) {
          const token = sessionStorage.getItem('token')
          let res = await axios.get('/category/findAll', {
            headers: {
              'Authorization': token
            }
          })
          commit('SET_CATEGORY', res.data.data)
        }
      }
    }

    // 3.声明状态机实例
    let store = new Vuex.Store({
      modules: {
        login: moduleLogin,
        category: moduleCategory
      }
    })

    let vm = new Vue({
      el: '#app',
      data: {},
      methods: {

      },
      created() {

      },
      components: {

      },
      router,
      store
    })
  </script>
</body>

</html>